package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.config.RabbitMQConfig;
import com.itheima.dao.BlogDao;
import com.itheima.dao.BlogSortDao;
import com.itheima.dao.BlogTagDao;
import com.github.pagehelper.Page;
import com.itheima.dao.PictureDao;
import com.itheima.pojo.Blog;
import com.itheima.pojo.BlogSort;
import com.itheima.pojo.Picture;
import com.itheima.pojo.Tag;
import com.itheima.service.BlogService;
import com.itheima.service.BlogTagService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.IdWorker;
import com.itheima.utils.MessageConstant;
import com.itheima.utils.ResultUtil;
import com.itheima.utils.StringUtils;
import com.itheima.utils.StringUtils;
import com.itheima.vo.BlogVO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BlogDao blogDao;

    @Autowired
    private BlogSortDao blogSortDao;

    @Autowired
    private BlogTagService blogTagService;

    @Autowired
    private BlogTagDao blogTagDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PictureDao pictureDao;



    //新增博客
    @Override
    public void add(BlogVO blogVO) {
            Blog blog = new Blog();
            //雪花算法生成uid
            long uid = idWorker.nextId();
            String stringUid = String.valueOf(uid);
            blog.setUid(stringUid);
            //将uid传入到search模块中
//        blogServiceFegin.addElasticSearchIndexByUid(stringUid);
            System.out.println("stringUid = " + stringUid);
            rabbitTemplate.convertAndSend(RabbitMQConfig.BLOG_ADD_EXCHANGE,"",stringUid);

            //标题 前端传
            blog.setTitle(blogVO.getTitle());
            //简介 前端传
            blog.setSummary(blogVO.getSummary() == null ? null : blogVO.getSummary());
            //文章内容
            blog.setContent(blogVO.getContent());

            //从VO中取出标签列表uid拼接成String
            List<Tag> tagList = blogVO.getTagList();
            StringBuilder stringBuilder = new StringBuilder();
            String resultUid = "";
            if (tagList != null && tagList.size() > 0) {
                for (Tag tag : tagList) {
                    String tagUid = tag.getUid();
                    stringBuilder.append(tagUid).append(",");
                    resultUid = stringBuilder.substring(0, stringBuilder.length() - 1).toString();
                }
            }

            blog.setTagUid(resultUid);

            blog.setClickCount(0);
            blog.setCollectCount(0);
            //图片uid 前端传
            blog.setFileUid(blogVO.getFileUid() == null ? null : blogVO.getFileUid());
            blog.setStatus(1);
            blog.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            blog.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            blog.setAdminUid(blogVO.getAdminUid());
            //是否原创
            blog.setIsOriginal(Integer.parseInt(blogVO.getIsOriginal()));
            blog.setAuthor(blogVO.getAuthor());
            blog.setArticlesPart(blogVO.getArticlesPart());
            //博客分类uid
            blog.setBlogSortUid(blogVO.getBlogSortUid());
            //推荐等级
            blog.setLevel(blogVO.getLevel());
            //是否发布
            blog.setIsPublish(Integer.parseInt(blogVO.getIsPublish()));
            blog.setSort(0);
            //是否开启网站评论
            blog.setStartComment(Integer.parseInt(blogVO.getStartComment()));

            blogDao.insertSelective(blog);

    }

    //删除博客
    @Override
    public void delete(BlogVO blogVO) {
        Blog blog = new Blog();
        //从前台获取uid
        blog.setUid(blogVO.getUid());
        blog.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        blog.setStatus(0);
        blogDao.updateByPrimaryKeySelective(blog);

    }

    @Override
    public void deleteBatch(BlogVO blogVO) {
        String uids = blogVO.getUid();
        String[] split = uids.split(",");
        if (split != null && split.length > 0) {
            for (String s : split) {
                Blog blog = new Blog();
                blog.setUid(s);
                blog.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                blog.setStatus(0);
                blogDao.updateByPrimaryKeySelective(blog);
            }
        }

    }

    //编辑博客
    @Override
    public void edit(BlogVO blogVO) {
        Blog blog = new Blog();
        //从前台获取uid
        blog.setUid(blogVO.getUid());
        //标题 前端传
        blog.setTitle(blogVO.getTitle());
        //简介 前端传
        blog.setSummary(blogVO.getSummary() == null ? null : blogVO.getSummary());
        //文章内容
        blog.setContent(blogVO.getContent());

        blog.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //从VO中取出标签列表uid拼接成String
        List<Tag> tagList = blogVO.getTagList();
        StringBuilder stringBuilder = new StringBuilder();
        String resultUid = "";
        if (tagList != null && tagList.size() > 0) {
            for (Tag tag : tagList) {
                String tagUid = tag.getUid();
                stringBuilder.append(tagUid).append(",");
                resultUid = stringBuilder.substring(0, stringBuilder.length() - 1).toString();
            }
        }

        blog.setTagUid(resultUid);

        //图片uid 前端传
        blog.setFileUid(blogVO.getFileUid() == null ? null : blogVO.getFileUid());
        //是否原创
        blog.setIsOriginal(Integer.parseInt(blogVO.getIsOriginal()));
        //博客分类uid
        blog.setBlogSortUid(blogVO.getBlogSortUid());
        //推荐等级
        blog.setLevel(blogVO.getLevel());
        //是否发布
        blog.setIsPublish(Integer.parseInt(blogVO.getIsPublish()));
        //是否开启网站评论
        blog.setStartComment(Integer.parseInt(blogVO.getStartComment()));
        blogDao.updateByPrimaryKeySelective(blog);
    }

    //获取博客列表
    @Override
    public Page<Blog> getList(BlogVO blogVO) {

        //取到传递过来的当前页
        Integer currentPage = blogVO.getCurrentPage();
        //非空校验，默认当前页为1
        if (currentPage == null || currentPage == 0) {
            currentPage = 1;
        }

        //取到传递过来的页面展示条数
        Integer pageSize = blogVO.getPageSize();
        if (pageSize == null || pageSize == 0) {
            pageSize = 10;
        }

        //利用PageHelper进行分页，传入当前页和展示条数
        PageHelper.startPage(currentPage, pageSize);

        //调用createExample方法传入blogVO，创建查询条件
        Example example = createExample(blogVO);

        //拿到Page对象
        Page<Blog> blogPage = (Page<Blog>) blogDao.selectByExample(example);

        //拿到pageResult
        List<Blog> pageResult = blogPage.getResult();

        if (pageResult != null && pageResult.size() > 0) {
            //遍历
            for (Blog blog : pageResult) {

                List<Tag> tagList = new ArrayList<Tag>();

                List<String> stringList = new ArrayList<String>();

                //拿到tagUid
                String tagUid = blog.getTagUid();

                String blogSortUid = blog.getBlogSortUid();

                String fileUid = blog.getFileUid();

                //判断是否只有一个uid，直接查
                if (tagUid.length() <= 32) {
                    if (tagUid != null && !"".equals(tagUid)) {
                        //查询出来之后再封装
                        Tag tag = blogTagDao.selectByPrimaryKey(tagUid);

                        if (tag != null && !"".equals(tag)) {

                            tagList.add(tag);
                            blog.setTagList(tagList);
                        }
                    }
                } else {
                    //包含“，”说明有多个uid
                    if (StringUtils.isNotEmpty(tagUid)) {
                        List<String> strList = StringUtils.changeStringToString(tagUid, ",");

                        //遍历字符串数组
                        for (String strItem : strList) {
                            //查询出来之后再封装
                            Tag tag = blogTagDao.selectByPrimaryKey(strItem);
                            if (tag != null && !"".equals(tag)) {
                                //添加到集合
                                tagList.add(tag);
                            }
                        }

                        //将标签集合封装到博客对象
                        blog.setTagList(tagList);
                    }
                }

                if (blogSortUid != null && !"".equals(blogSortUid)) {
                    BlogSort blogSort = blogSortDao.selectByPrimaryKey(blogSortUid);

                    if (blogSort != null & !"".equals(blogSort)) {

                        blog.setBlogSort(blogSort);
                    }
                }

            }
        }

        return blogPage;
    }

    //通过uid获取博客


    @Override
    public Blog getBlogByUid(String uid) {
        Blog blog=blogDao.selectByPrimaryKey(uid);
        return blog;
    }

    //通过uid获取博客点赞数
    @Override
    public Integer getBlogPraiseCountByUid(String uid) {
        Blog blog=blogDao.selectByPrimaryKey(uid);
        if(blog==null){
            return null;
        }
        Integer clickCount=blog.getClickCount();
        return clickCount;
    }

    //根据bloguid获取同类型的博客
    @Override
    public List<Blog> getSameBlogByBlogUid(String blogUid) {
        Blog blog=blogDao.selectByPrimaryKey(blogUid);
        if(blog==null){
            return null;
        }
        String blogsortUid=blog.getBlogSortUid();
        if(StringUtils.isEmpty(blogsortUid)){
            return null;
        }
        Example example=new Example(Blog.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("status",1);
        criteria.andEqualTo("blogsortuid",blogsortUid);
        List<Blog> blogList = blogDao.selectByExample(example);
        return blogList;
    }

    @Override
    public Page<Blog> getSameBlogByTagUid(String tagUid, Long currentPage, Long pageSize) {
        Tag tag = blogTagService.getTagByUid(tagUid);
        if (tag==null){
            return null;
        }

        PageHelper.startPage(currentPage.intValue(),pageSize.intValue());
        Example example = new Example(Blog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",1);
        criteria.andEqualTo("tagUid",tagUid);
        Page<Blog> blogList = (Page<Blog>)blogDao.selectByExample(example);
        return blogList;

    }


    //通过uid给博客点赞
    @Override
    public String praiseBlogByUid(String uid) {
        Blog blog=blogDao.selectByPrimaryKey(uid);
        if(blog==null){
            return ResultUtil.result("401", MessageConstant.BLOG_NULL_FAIL);
        }
        Integer clickCount=blog.getClickCount();
        blog.setClickCount(clickCount+1);
        blogDao.updateByPrimaryKeySelective(blog);
        return ResultUtil.result("200",MessageConstant.BLOG_CLICKCOUNT_SUCCESS);

    }

    /**
     * 构建查询对象
     * @param blogVO
     * @return
     */
    private Example createExample(BlogVO blogVO) {
        Example example = new Example(Blog.class);
        Example.Criteria criteria = example.createCriteria();
        if (blogVO != null) {
            // 博客名
            if (blogVO.getTitle() != null && !"".equals(blogVO.getTitle())) {
                criteria.andLike("title", "%" + blogVO.getTitle() + "%");
            }

            // 分类名
            String sortUid = blogVO.getBlogSortUid();
            if (sortUid != null && !"".equals(sortUid)) {
                criteria.andEqualTo("blogSortUid", sortUid);
            }

            // 标签名
            List<Tag> tagList = blogVO.getTagList();
            if (tagList != null && tagList.size() > 0) {
                for (Tag tag : tagList) {
                    String tagUid = tag.getUid();
                    criteria.andEqualTo("tagUid", tagUid);
                }
            }

            // 推荐等级
            Integer level = blogVO.getLevel();
            if (level != null && !"".equals(level)) {
                criteria.andEqualTo("level", level);
            }
            // 是否发布
            String isPublish = blogVO.getIsPublish();
            if (isPublish != null && !"".equals(isPublish)) {
                criteria.andEqualTo("isPublish", isPublish);
            }
            // 是否原创
            String isOriginal = blogVO.getIsOriginal();
            if (isOriginal != null && !"".equals(isOriginal)) {
                criteria.andEqualTo("isOriginal", isOriginal);
            }
            //状态为1的才显示
            criteria.andEqualTo("status", 1);
        }
        return example;
    }

    public Map<String, Object> getBlogContributeCount() {
        //获取当前时间
        String nowTime = DateUtils.getNowTime();
        //获取一年前时间
        Date date = DateUtils.getDate(nowTime, -365);
        String startTime = DateUtils.dateTimeToStr(date);
        //获取一年内的文章贡献度
        List<Map<String, Object>> blogContributeMap = blogDao.getBlogContributeCount(startTime, nowTime);
        Map<String, Object> dateMap = new HashMap<>();
        for (Map<String, Object> stringObjectMap : blogContributeMap) {
            dateMap.put(stringObjectMap.get("DATE").toString(),stringObjectMap.get("COUNT"));
        }
        //获取一年内所有时间
        List<String> dateList = DateUtils.getDayBetweenDates(startTime, nowTime);
        List<List<Object>> resultList = new ArrayList<>();
        for (String s : dateList) {
            Integer count=0;
            if (dateMap.get(s)!=null){
                count=Integer.valueOf(dateMap.get(s).toString());
            }
            List<Object> objectList = new ArrayList<>();
            objectList.add(s);
            objectList.add(count);
            resultList.add(objectList);
        }
        Map<String, Object> resultMap = new HashMap<>();

        //获取查询时间集合
        List<String> contributeDateList = new ArrayList<>();
        contributeDateList.add(startTime);
        contributeDateList.add(nowTime);

        resultMap.put("contributeDate", contributeDateList);
        resultMap.put("blogContributeCount", resultList);
        return resultMap;
    }

    //通过推荐登级获取博客列表
    @Override
    public List<Blog> getBlogByLevel(Integer level, Integer currentPage, Integer useSort) {
        if(currentPage==null||currentPage<1){
            currentPage=1;
        }
        PageHelper.startPage(currentPage,10);
        Example example=new Example(Blog.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("level",level);
        if(useSort==0){
            //若果useSort=0，升序
            example.orderBy("sort").asc();
        }
        example.orderBy("sort").desc();
        List<Blog> blogList = blogDao.selectByExample(example);
        return blogList;
    }

    //按时间戳获取博客
    public List<Blog> getBlogByTime(Integer currentPage, Integer pageSize, String startDate, String endDate) {
        if(currentPage==null||currentPage<1){
            currentPage=1;
        }
        if(pageSize==null||pageSize==0){
            pageSize=10;
        }
        PageHelper.startPage(currentPage,pageSize);
        Example example=new Example(Blog.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andBetween("creatTime",startDate,endDate);
        List<Blog> blogList = blogDao.selectByExample(example);
        return blogList;
    }

    //获取首页排行博客
    @Override
    public List<Blog> getHotBlog() {
       PageHelper.startPage(1,10);
       Example example=new Example(Blog.class);
       example.orderBy("clickCount").desc();
        List<Blog> blogList = blogDao.selectByExample(example);
        return blogList;
    }

    //获取首页最新的博客
    @Override
    public List<Blog> getNewBlog(Integer curretnPage, Integer pageSize) {
        if(curretnPage==null||curretnPage<1){
            curretnPage=1;
        }
        if(pageSize==null||pageSize==0){
            pageSize=10;
        }
        PageHelper.startPage(curretnPage,pageSize);
        Example example=new Example(Blog.class);
        example.orderBy("creatTiem").desc();
        List<Blog> blogList = blogDao.selectByExample(example);
        return blogList;
    }

    //获取每个分类下文章数目
    @Override
    public List<Map<String, Object>> getBlogCountByBlogSort() {
        //获取每个分类下文章数目
        List<Map<String, Object>> blogCountByBlogMap = blogDao.getBlogCountByBlogSort();
        Map<String, Integer> blogSortMap = new HashMap<>();
        for (Map<String, Object> stringObjectMap : blogCountByBlogMap) {
            String blogSortUid = String.valueOf(stringObjectMap.get("blog_sort_uid"));
            Number num = (Number) stringObjectMap.get("count");
            Integer count = 0;
            if (num != null) {
                count = num.intValue();
            }
            blogSortMap.put(blogSortUid, count);
        }
        //把查询到的BlogSort放到Map中
        Set<String> blogSortUids = blogSortMap.keySet();
        Collection<BlogSort> blogSortCollection = new ArrayList<>();
        if (blogSortUids.size() > 0) {
            for (String blogSortUid : blogSortUids) {
                BlogSort blogSort = blogSortDao.selectByPrimaryKey(blogSortUid);
                if (blogSort!=null){
                    ((ArrayList<BlogSort>) blogSortCollection).add(blogSort);
                }
            }
        }

        Map<String, String> blogSortEntityMap = new HashMap<>();
        for (BlogSort blogSort : blogSortCollection) {
            if (StringUtils.isNotEmpty(blogSort.getSortName())) {
                blogSortEntityMap.put(blogSort.getUid(), blogSort.getSortName());
            }
        }
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
        for (Map.Entry<String, Integer> entry : blogSortMap.entrySet()) {

            String blogSortUid = entry.getKey();

            if (blogSortEntityMap.get(blogSortUid) != null) {
                String blogSortName = blogSortEntityMap.get(blogSortUid);
                Integer count = entry.getValue();

                Map<String, Object> itemResultMap = new HashMap<>();
                itemResultMap.put("blogSortUid", blogSortUid);
                itemResultMap.put("name", blogSortName);
                itemResultMap.put("value", count);
                resultMap.add(itemResultMap);
            }
        }
        return resultMap;
    }

    //获取每个标签下文章数
    @Override
    public List<Map<String, Object>> getBlogCountByTag() {
        List<Map<String, Object>> blogCountByTag = blogDao.getBlogCountByTag();
        Map<String, Integer> tagMap = new HashMap<>();
        for (Map<String, Object> map : blogCountByTag) {
            String tagUid = String.valueOf(map.get("tag_uid"));
            //Number是Integer,Long的父类
            Number number = (Number)map.get("count");
            Integer count = number.intValue();

            //判断是否只有一个uid
            if (tagUid.length() <= 32){
                //判断有没有内容
                if (tagMap.get(tagUid) == null){
                    tagMap.put(tagUid,count);
                }else {
                    Integer tempCount = tagMap.get(tagUid) + count;
                    tagMap.put(tagUid, tempCount);
                }
            }else {
                //包含“，”说明有多个uid
                if (StringUtils.isNotEmpty(tagUid)) {
                    List<String> strList = StringUtils.changeStringToString(tagUid, ",");
                    for (String strItem : strList) {
                        if (tagMap.get(strItem) == null) {
                            tagMap.put(strItem, count);
                        } else {
                            Integer tempCount = tagMap.get(strItem) + count;
                            tagMap.put(strItem, tempCount);
                        }
                    }
                }
            }
        }
        //把查询到的Tag放到Map中
        Set<String> tagUids = tagMap.keySet();
        Collection<Tag> tagCollection = new ArrayList<>();

        if (tagUids.size() > 0) {
            for (String tagUid : tagUids) {
                Tag tag = blogTagDao.selectByPrimaryKey(tagUid);
                if (tag!=null){
                    tagCollection.add(tag);
                }
            }
        }

        Map<String, String> tagEntityMap = new HashMap<>();
        for (Tag tag : tagCollection) {
            if (StringUtils.isNotEmpty(tag.getContent())) {
                tagEntityMap.put(tag.getUid(), tag.getContent());
            }
        }

        List<Map<String, Object>> resultMap = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : tagMap.entrySet()) {

            String tagUid = entry.getKey();

            if (tagEntityMap.get(tagUid) != null) {
                String tagName = tagEntityMap.get(tagUid);
                Integer count = entry.getValue();

                Map<String, Object> itemResultMap = new HashMap<>();
                itemResultMap.put("tagUid", tagUid);
                itemResultMap.put("name", tagName);
                itemResultMap.put("value", count);
                resultMap.add(itemResultMap);
            }
        }
        System.out.println(resultMap);
        return resultMap;
    }

    @Override
    public Integer getBlogCount() {
        Blog blog = new Blog();
        blog.setStatus(1);
        blog.setIsPublish(1);
        return blogDao.selectCount(blog);
    }
}
